from rest_framework import serializers
from user import models
from rest_framework.exceptions import ValidationError


class UserCRUDSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ['dept', 'email', 'enabled', 'gender', 'id', 'jobs', 'nickName', 'phone', 'roles', 'username']

    dept = serializers.CharField(read_only=True)
    jobs = serializers.CharField(read_only=True)
    nickName = serializers.CharField(read_only=True)
    roles = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['create_by'] = request.user.username
        attrs['is_superuser'] = False
        attrs['nick_name'] = request.data.get('nickName')
        attrs['password'] = '123456'  # 默认密码
        return attrs

    def create(self, validated_data):
        request = self.context.get('request')
        jobs_list = [job.get('id') for job in request.data.get('jobs')]
        roles_list = [role.get('id') for role in request.data.get('roles')]
        dept = request.data.get('dept').get('id')
        validated_data['dept_id'] = dept
        user = models.UserInfo.objects.create_user(**validated_data)
        user.job.add(*jobs_list)
        user.roles.add(*roles_list)
        return user


class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ['avatarPath', 'createBy', 'createTime', 'dept','jobs', 'nickName', 'roles', 'updateBy', 'updateTime',
                  'email', 'enabled', 'gender', 'id', 'phone', 'username']

    avatarPath = serializers.CharField(read_only=True)
    createBy = serializers.CharField(read_only=True)
    createTime = serializers.CharField(read_only=True)
    dept = serializers.CharField(read_only=True)
    jobs = serializers.CharField(read_only=True)
    nickName = serializers.CharField(read_only=True)
    roles = serializers.CharField(read_only=True)
    updateBy = serializers.CharField(read_only=True)
    updateTime = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['update_by'] = request.user.username
        return attrs

    def update(self, instance, validated_data):
        request = self.context.get('request')
        jobs_list = [job.get('id') for job in request.data.get('jobs')]
        roles_list = [role.get('id') for role in request.data.get('roles')]
        dept = request.data.get('dept').get('id')
        validated_data['dept_id'] = dept
        validated_data['nick_name'] = request.data.get('nickName')
        models.UserInfo.objects.filter(pk=instance.pk).update(**validated_data)
        instance.job.clear()
        instance.roles.clear()
        instance.job.add(*jobs_list)
        instance.roles.add(*roles_list)
        # instance.save()
        return instance


class UserCenterSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ['newPass', 'oldPass']

    newPass = serializers.CharField(read_only=True)
    oldPass = serializers.CharField(read_only=True)

    def validate(self, attrs):
        """
        这个修改是修改当前登录用户的密码， 现判断老密码
        :param attrs:
        :return:
        """
        request = self.context.get('request')
        attrs['newPass'] = request.data.get('newPass')
        old_password = request.data.get('oldPass')
        user = request.user
        if user.check_password(old_password):
            return attrs
        else:
            raise ValidationError('原密码错误')


    def create(self, validated_data):
        request = self.context.get('request')
        user = request.user
        user.set_password(validated_data.get('newPass'))
        user.save()
        return user


class UserCenterEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields  =['email', 'password']

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['update_by'] = request.user.username
        return attrs

    def update(self, instance, validated_data):
        validated_data.pop('password')
        return super().update(instance, validated_data)


class UserUpdateInfoCentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ['gender', 'id', 'nickName', 'phone']

    nickName = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['nick_name'] = request.data.get('nickName')
        return attrs

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)


class UserCenterUpdateAvater(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ['avatar']

    avatar = serializers.CharField(read_only=True)

    def create(self, validated_data):
        request = self.context.get('request')
        avatar = request.data.get('avatar')
        user = models.UserInfo.objects.filter(pk=request.user.pk).first()
        user.avatar_path = avatar
        user.save()
        return user